package com.zszq.ms.bigmodeltest.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * pdf处理工具类
 *
 * @author ms
 * @since 2025/03/28
 */
public class PdfUtils {

    /**
     * 根据页码拆分pdf
     *
     * @param filePath pdf全路径地址
     * @return 分页数据集合
     * @throws IOException 读取pdf文件异常
     */
    public static List<String> getPageTextByPage(String filePath) throws IOException {
        File file = new File(filePath);
        List<String> pages = new ArrayList<>();
        try (PDDocument document = PDDocument.load(file)) {
            int totalPages = document.getNumberOfPages();
            PDFTextStripper pdfStripper = new PDFTextStripper();
            for (int i = 1; i <= totalPages; i++) {
                pdfStripper.setStartPage(i);
                pdfStripper.setEndPage(i);
                String pageContent = pdfStripper.getText(document);
                pages.add(pageContent);
            }
        }
        return pages;
    }

    /**
     * 根据页码拆分pdf并封装为PdfTextInfo对象
     *
     * @param filePath pdf全路径地址
     * @return PdfTextInfo对象
     * @throws IOException 读取pdf文件异常
     */
    public static List<PdfTextInfo> getPdfTextInfoByPage(String filePath) throws IOException {
        File file = new File(filePath);
        List<PdfTextInfo> pages = new ArrayList<>();
        try (PDDocument document = PDDocument.load(file)) {
            int totalPages = document.getNumberOfPages();
            PDFTextStripper pdfStripper = new PDFTextStripper();
            for (int i = 1; i <= totalPages; i++) {
                pdfStripper.setStartPage(i);
                pdfStripper.setEndPage(i);
                String pageContent = pdfStripper.getText(document);
                PdfTextInfo pdfTextInfo = new PdfTextInfo();
                pdfTextInfo.setPageIndex(i);
                pdfTextInfo.setPageText(pageContent);
                pdfTextInfo.setLastLine(getLastLines(pageContent));
                pages.add(pdfTextInfo);
            }
        }
        return pages;
    }

    /**
     * 获取pdf每页最后一行数据
     *
     * @param pageText 每页所有数据
     * @return 每页最后一行数据
     */
    public static String getLastLines(String pageText) {
            // 按换行符分割
            String[] lines = pageText.split("\n");
            if (lines.length > 0) {
                // 获取最后一行
                return lines[lines.length - 1].trim();
            } else {
                // 如果页面为空，添加空字符串
                return "";
            }
    }
}
